package com.example.ffepeg.ffeAdder;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DataSegmenter {

    private static final double TIME_PER_CHAR = 0.2; // 每个字符代表0.2秒
    private static final double MAX_TIME = 6.0;      // 超过6秒就截断

    public static void main(String[] args) {
        String dataStream = "发的说法是的法师打发三大发阿阿斯顿法师打发是的阿斯蒂芬自行承担放大广发多尴尬发法师打发三大发阿斯顿法师打发手动阀手打都是发生的发生的发生的手动阀手动阀手动阀手动阀手动阀手动阀手动阀手动阀手动阀娃儿额万达出发代发萨达发都发";
        String dfe = "<speak>噫吁嚱，危乎高哉！蜀道之难，难于上青天！蚕丛及鱼凫，开国何茫然！尔来四万八千岁，不与秦塞通人烟。西当太白有鸟道，可以横绝峨眉巅。地崩山摧壮士死，然后天梯石栈相钩连。上有六龙回日之高标，下有冲波逆折之回川。黄鹤之飞尚不得过，猿猱欲度愁攀援。</speak>";
        List<String> list = extractedPart(dataStream);
        System.out.println(list);


        /*  List<String> segments = segmentData(dfe);
        // 输出所有截取的段落
        for (String segment : segments) {
            System.out.println(segment);
        }*/
    }

    public static List<String> segmentData(String dataStream) {
        List<String> segments = new ArrayList<>();
        StringBuilder currentSegment = new StringBuilder();
        double currentTime = 0.0;

        for (char ch : dataStream.toCharArray()) {
            currentSegment.append(ch);
            currentTime += TIME_PER_CHAR;

            if (currentTime >= MAX_TIME) {
                segments.add(currentSegment.toString());
                currentSegment = new StringBuilder(); // 重置当前段
                currentTime = 0.0; // 重置时间
            }
        }

        if (currentSegment.length() > 0) {
            segments.add(currentSegment.toString());
        }

        return segments;
    }

    private static List<String> extractedPart(String ssmlString){
        List<String> extractedParts = new ArrayList<>();
        if (ssmlString.startsWith("<speak>") && ssmlString.endsWith("</speak>")) {
            ssmlString = ssmlString.substring(7, ssmlString.length() - 8);
        }
        String patternString = "(.*?)(<break time='\\d+ms'/>)";
        Pattern pattern = Pattern.compile(patternString, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(ssmlString);
        int lastEndIndex = 0;
        while (matcher.find()) {
            if (matcher.start() > lastEndIndex) {
                extractedParts.add(ssmlString.substring(lastEndIndex, matcher.start()).trim());
            }
            extractedParts.add(matcher.group().trim());
            lastEndIndex = matcher.end();
        }
        if (lastEndIndex < ssmlString.length()) {
            extractedParts.add(ssmlString.substring(lastEndIndex).trim());
        }
        return extractedParts;
    }
}